//
//  inputMixer.m
//  Wi-Fi Party remade-1
//
//  Created by Vieta Ken on 2021/4/16.
//

#import "inputMixer.h"

@implementation inputMixer

-(id)init{
    self=[super init];
    self->result=[[Queue alloc] init];
    self->tracks=[[NSMutableDictionary alloc] init];
    self->dispatch_queue=dispatch_queue_create("inputMixer dispatch queue", DISPATCH_QUEUE_CONCURRENT);
    self->mixing=false;
    self->length=realIOBufferDuration*SAMPLE_RATE*BYTES_PER_FRAME;
    {   //send_socket
        int flag=1;
        self->send_socket=socket(AF_INET,SOCK_DGRAM,0);
        setsockopt(self->send_socket, SOL_SOCKET, SO_BROADCAST, &flag, sizeof(flag));
        //send_addr
        self->send_addr.sin_family=AF_INET;
        self->send_addr.sin_port=htons(PORT);
        self->send_addr.sin_addr.s_addr=inet_addr("255.255.255.255");
    }
    return self;
}

-(void)addAudioSegment:(const signed char *)buffer ofSize:(int)size from:(id)sender{
    if(!([[self->tracks allKeys] containsObject:sender])){
        self->tracks[sender]=[[Queue alloc] init];
    }
    [self->tracks[sender] writeData:buffer size:size];
}

-(void)setTrack: (Queue *)track from:(id)sender{
    self->tracks[sender]=track;
}

-(void)flush{
    extern NSTimeInterval realIOBufferDuration;
    static unsigned long long packetNumber=0;
    
    cleanup(self->tracks);
    NSArray* allTracks=[self->tracks allValues];
    if([allTracks count]!=0){
        packetNumber++;
        mix_audio_streams([self->tracks allValues], length, self->result);
        partyPacket *packet=[[partyPacket alloc] init:length];
        [packet setNumber:packetNumber];
        [self->result readAndWriteTo:[packet getPayloadAddr] size:length];
        [packet send:self->send_socket toAddr:&self->send_addr];
    }
}


-(void)dealloc{
    close(self->send_socket);
}

@end
